//产品线 0 蜜哆哆 1 蜜雅阁 2 品牌馆
var cateType = 0;

var curCatePath = "未选择分组";

$(function () {
    create_tree(cateType);//生成树

    //初始化banner图dropzone设置
    initGroupBannerPics();
    var instance = $('#jstree_demo').jstree(true);
    selectCurPath();
});

//点选节点显示路径
function selectCurPath() {
    $('#jstree_demo').on("select_node.jstree", function (e, data) {
        var instance = $('#jstree_demo').jstree(true);
        curCatePath = data.instance.get_path(data.selected[0], ">", 0);
        //获取当前选择目录路径
        console.log("selected的data数据", data.instance.get_path(data.selected[0], ">", 0));
        $("#curCatePath").text(curCatePath);
    });
}

function lv1_create() {
    var instance = $('#jstree_demo').jstree(true);
    instance.deselect_all();
    sel = instance.get_selected();
    if (!sel.length) {
        cateType = $("#cateType").val();
        node_create(instance, true, cateType);
    }
};

$("#cateType").change(function () {
    // 初始化原详情
    initGroupDetail();
    cateType = $("#cateType").val();
    console.log(cateType);
    $.jstree.destroy('#jstree_demo');
//        $('#jstree_demo').empty();
    create_tree(cateType);
});

//新建node
function node_create(instance, if_root, cateType) {
    var parent;
//        是否是新建根节点
    if (if_root) {
        instance.deselect_all();
        parent = "#";
    } else {
        //当前是否有选中的节点
        if (instance.get_selected().length = 0)
            return;
        parent = instance.get_selected()[0];
    }
    instance.create_node(parent, {
        "text": "",
        "type": "root"
    }, "last", function (node) {
        instance.deselect_all();
        instance.select_node(node.id);
        //启用编辑，编辑后才保存新建的node
        instance.edit(node.id, "", function (data) {
            if (data.text == "") {
                alert("名称不能为空");
                instance.delete_node(node.id);
                return;
            }
            var postdata = "{";
            postdata += '"title":"' + data.text + '"';
            postdata += ',"groupType":"' + cateType + '"';
            if (!if_root)
                postdata += ',"pid":"' + parent + '"';
            postdata += "}";
            console.log(data);
            $.ajax({
                type: "post",
                url: urlcore + "/api/indexGroup/add",
                contentType: "application/json;charset=utf-8",
                data: postdata,
                success: function (cbdata) {
                    var id = parseInt(cbdata.data.id);
                    // $(data.rslt.obj).attr("id", "li_" + data1.d);
                    instance.set_id(node, id);
                    instance.deselect_all();
                    instance.select_node(id);
                    console.log("- -insert and update success,data:" + cbdata);
                },
                error: function () {
                    alert("添加失败，请刷新后重试");
                }
            });
        });
    });

}

function create_tree(cateType) {
    $.ajax({
        url: urlcore + "/api/indexGroup/getTree",
        type: "get",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        dataType: "json",
        data: {cateType: cateType},
        success: function (treedata) {
            console.log(treedata);
            $('#jstree_demo').on("select_node.jstree", function (e, data) {
                var instance = $('#jstree_demo').jstree(true);
                console.log("selected的data数据", data.selected);
            }).on("changed.jstree", function (e, data) {
                //刷新fileinput插件
                $("#fileupload2").fileinput("refresh");
                //清空记录的旧图信息
                $("#oldpic").html("");
                //初始化当前路径
                curCatePath = "";
                //当有节点被选中时
                if (data.selected.length) {
                    var slcnode = {
                        id: data.node.id,
                        parent: data.node.parent,
                        text: data.node.text
                    };
                    console.log(slcnode);
                    console.log('The selected node\'s is: ' + data.instance.get_node(data.selected[0]).text);
                    console.log("selected node original data is :", data.node.original);
                    //业务，更改产品线之后destroy树后选择事件失效
                    /*  形如
   original:
   {id:50
   parent:"49"
   picture_url:"http://127.0.0.1:8080//ATTACHMENT/0b75295b-df1e-4860-a5ce-390c467c8856/d7341d16-8bb4-4402-82f0-330056fb7f96.jpg"
   subtitle:"这是出生地的分类描述"
   text:"出生地"}
   */
                    var original = data.node.original;
                    console.log("original:", original);
                    //取出选中树节点的源数据
                    $("#subtitle").val(original.subtitle);
                    var picSrc = original.picture_url;
                    if (picSrc == undefined) {
                        $('#previous_picture_div').hide();
                    } else {
                        $('#previous_picture_div').css("display", "block");
                        var imgStr1 = "";
                        //多图数组
                        picSrc = picSrc.split(",");
                        $.each(picSrc, function (index, value) {
                            if (value != "") {
                                imgStr1 +=
                                    '<div style="position:relative;width:180px;height:auto;float:left;" display="block">' +
                                    '	<img style="padding: 5px 5px 5px 5px;" width="auto" height="150px" src="' + value + '">' +
                                    '</div>';
                            }

                        });
                        $('#pictureUrl').html(imgStr1);
                    }
                    //获取当前选择目录路径
                    var instance = $('#jstree_demo').jstree(true);
                    curCatePath = data.instance.get_path(data.selected[0], ">", 0);

                    console.log("selected的data数据", data.instance.get_path(data.selected[0], ">", 0));
                    $("#curCatePath").text(curCatePath);
                    //业务
                }
            })
                .jstree({
                    'core': {
                        'multiple': false,
                        'check_callback': function (operation, node, parent, position, more) {
                            if (operation === 'create_node') {
                                console.log('create测试');
                                console.log('create测试的parent.id=', parent.id, ',create测试的parent.text=', parent.text);
                                // node.id="zzzz";
                            }
                            if (operation === 'delete_node') {
                                console.log('delete测试');
                                console.log("delete节点的id=", node.id, ",delete节点的text=", node.text)
                                console.log(node.text);
                                console.log(position);

                            }
                            if (operation === 'rename_node') {
                                console.log('rename测试');
                                console.log("rename节点的id=", node.id)
                                console.log("parent.id:", parent.id, ",parent.text:", parent.text);
                                console.log("原来text:", node.text, ",rename后的text:", position);

                            }
                            console.log('测试区域');
                            return true;
                        },
                        'data': treedata
                    },
                    'plugins': [ //插件，下面是插件的功能
                        'types', //可以设置其图标，在上面的一样。
                        'contextmenu', //文本菜单
                        'wholerow', //
//                    'sort', //排序，添加node后会自动排序，影响回调中的编辑操作
                        // 'unique', //独特----防止重复。(新添加的)
//                    'dnd', //提供拖放功能
                        'search' //启用搜索
                    ],
                    'types': {
                        "#": {
                            "max_depth": 2,
                            "valid_children": ["root"]
                        }
                    },
                    'contextmenu': {
                        "items": {
                            "create": {
                                "label": "新增",
                                "action": function () {
                                    var instance = $('#jstree_demo').jstree(true);
                                    var cur = instance.get_selected();
                                    //当前节点为父节点新建node
                                    node_create(instance, false, cateType);
                                }
                            },
                            "rename": {
                                "label": "修改",
                                "action": function () {
                                    var instance = $('#jstree_demo').jstree(true);
                                    var cur = instance.get_selected();
                                    var oldtext = instance.get_node(cur).text;
                                    instance.edit(cur, null, function (data) {
                                        if (data.text == oldtext)
                                            return;
                                        if (data.text == "") {
                                            alert("名称不能为空!");
                                            return;
                                        }
                                        console.log(data);
                                        var postdata = "{";
                                        postdata += '"id":' + data.id + ',"title":"' + data.text + '"';
                                        // postdata+=',"classifyType":"'+data.parent+'"';
                                        postdata += "}";
                                        $.ajax({
                                            type: "post",
                                            url: urlcore + "/api/indexGroup/update",
                                            contentType: "application/json;charset=utf-8",
                                            data: postdata,
                                            success: function (cbdata) {
                                                console.log("--update success,data:" + cbdata);
                                            },
                                            error: function () {
                                                alert("修改失败，请刷新后重试!");
                                            }
                                        });
                                    });
                                }
                            },
                            "delete": {
                                "label": "删除",
                                "action": function () {
                                    var instance = $('#jstree_demo').jstree(true);
                                    var cur = instance.get_node(instance.get_selected());
                                    postdata = '{"id":"' + cur.id + '"';
                                    if (cur.children.length > 0) {
                                        if (!confirm("要删除的分组中还有数据，确定删除吗")) {
                                            return;
                                        }
                                        postdata += ',"rec":"1"';//级联删除其下的子节点
                                    }
                                    postdata += "}";
                                    $.ajax({
                                        type: "post",
                                        url: urlcore + "/api/indexGroup/delete",
                                        contentType: "application/json;charset=utf-8",
                                        data: postdata,
                                        success: function (cbdata) {
                                            console.log("--delete success,data:" + cbdata);
                                            console.log("---delete node", cur);
                                            instance.delete_node(cur);
                                        },
                                        error: function () {
                                            alert("删除失败，该分组下还有商品存在，请稍后再试");
                                        }
                                    });

                                }
                            }
                        }
                    }
                });
        },
        error: function () {
            alert("获取分组树失败，请刷新后重试");
        }
    });

}

//输入框输入定时自动搜索
var to = false;
$('#search_ay').keyup(function () {
    if (to) {
        clearTimeout(to);
    }
    to = setTimeout(function () {
        node_search();
    }, 250);
});
$('#btn_search').on('click', function () {
    node_search();
});

function node_search() {
    var instance = $('#jstree_demo').jstree(true);
    instance.deselect_all();
    instance.search($('#search_ay').val());
}

$('#btn_refresh_tree').on('click', function () {
    /*    var ins = $('#jstree_demo').jstree(true);
        ins.refresh();*/
    // 初始化原详情
    initGroupDetail();
    cateType = $("#cateType").val();
    console.log(cateType);
    $.jstree.destroy('#jstree_demo');
    curCatePath = "未选择分组";
    $("#curCatePath").text(curCatePath);//goods_add.js中的
//        $('#jstree_demo').empty();
    create_tree(cateType);
    selectCurPath();
});

//初始化banner图dropzone设置
function initGroupBannerPics() {
    // $("#groupBannerPics").dropzone({
    //
    // });
}

//初始化fileinput控件（第一次初始化）
function initGroupFileInput(ctrlName, uploadUrl, okName, maxnNum) {
    var control = $('#' + ctrlName);

    control.fileinput({
        language: 'zh', //设置语言
        uploadUrl: uploadUrl, //上传的地址
        //uploadExtraData:{"id": 1, "fileName":'123.mp3'},
        resizeImage: true,
        resizePreference: 'width',
        resizeImageQuality: 0.2,
        uploadAsync: true, //默认异步上传
        showUpload: true, //是否显示上传按钮
        showRemove: true, //显示移除按钮
        showPreview: true, //是否显示预览
        showCaption: false,//是否显示标题
        browseClass: "btn btn-primary", //按钮样式
        dropZoneEnabled: true,//是否显示拖拽区域
        maxFileCount: 4, //表示允许同时上传的最大文件个数
        dropZoneTitle: '拖拽文件到这里 &hellip;',
        enctype: 'multipart/form-data',
        validateInitialCount: true,
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
    }).on("fileuploaded", function (event, data, key) {
        if (data.response) {
            var okData = data.response.data;
            for (var i = 0; i < okData.length; i++) {
                var strHtml =
                    '<div style="position:relative;width:250px;height:250px;float:left;display:none" id="' + key + '">' +
                    '	<span onclick="removeStrHtml()" style="position:absolute;top:10px;right:10px;font-size:20px;color:#f00;" class="glyphicon glyphicon-trash" aria-hidden="true">' +
                    '	</span>' +
                    '	<img style="padding: 5px 5px 5px 5px;" width="250px" height="250px" src="' + okData[i] + '">' +
                    '</div>';
                $(okName).append(strHtml);
            }
        }
    }).on('filesuccessremove', function (event, key) {
        $("#" + key).remove();
    }).on('filecleared', function(event) {
        $(okName).html("");
        console.log("filecleared");
    });;
}

//刷新树或更改产品线后初始化基本信息
function initGroupDetail(){
    $("#oldpic").html("");
    $("#previous_picture_div").hide();
    $("#pictureUrl").html("");
    $("#subtitle").val("");
    //刷新fileinput插件
    $("#fileupload2").fileinput("refresh");
}